/**
 *  步骤添加
 */
(function ($) {
    var options = {
        index: {
            formatter: function (index) {
                return '<input type="text" class="easyui-textbox" style="border: 0px;" readonly value="第' + index + '步">';
            }
        },
        ctrls: [{
            type: 'combobox',
            name: '',
            param: {
                valueField: 'value',
                textField: 'text',
                url: '',
                data: [],
            }
        }, {
            type: 'textbox',
            text: '',
            name: '',
            style: {}
        }, {
            type: 'hidden',
            name: '',
        }, {
            type: 'label',
            text: '',
            style: {}
        }],
        ctrlOption: {
            combobox: {},
            textbox: {},
            label: {},
            hidden: {}
        },
        btn: {
            text: '',
            formatter: function (text) {
                return '<a class="easyui-linkbutton">' + text + '</a>';
            },
            add_click: function (index) {
            },
            remove_click: function (index, total) {
            }
        }
    };

    options.ctrlOption.combobox.init = function (ctrlOption) {
        var box = $(this);
        ctrlOption.name && ctrlOption.name.length && (box.attr('name', ctrlOption.name));
        box.combobox(ctrlOption.param);
        return box;
    }

    options.ctrlOption.textbox.init = function (ctrlOption) {
        var box = $(this);
        ctrlOption.name && ctrlOption.name.length && (box.attr('name', ctrlOption.name));
        ctrlOption.text && box.val(ctrlOption.text);
        if (ctrlOption.style) {
            for (st in ctrlOption.style) {
                box.css(st, ctrlOption.style[st]);
            }
        }
        box.textbox({});
        return box;
    }

    options.ctrlOption.label.init = function (ctrlOption) {
        var box = $(this);
        ctrlOption.text && box.html(ctrlOption.text);
        if (ctrlOption.style) {
            for (st in ctrlOption.style) {
                box.css(st, ctrlOption.style[st]);
            }
        }
        return box;
    }

    options.ctrlOption.hidden.init = function (ctrlOption) {
        var box = $(this);
        box.attr('type', 'hidden');
        ctrlOption.name && ctrlOption.name.length && (box.attr('name', ctrlOption.name));
        return box;
    }

    function parseOption(option) {
        var opt = {
            index: $.extend({}, options.index, option.index),
            btn: $.extend({}, options.btn, option.btn),
            ctrls: []
        };
        if (option.ctrls && option.ctrls.length) {
            option.ctrls.map(function (ctrl) {
                var type = options.ctrlOption[ctrl.type];
                if (type) {
                    opt.ctrls.push($.extend({}, type, ctrl));
                }
            })
        }
        return opt;
    }

    function currentStep(val) {
        var btn = $(this);
        if (val && (val * 1 > 0)) {
            return btn.data('current_step', val);
        }
        return btn.data('current_step') || 1;
    }

    function initWrapper(option, initReady) {
        var con = $(this);
        if (!$.isEmptyObject(con)) {
            con.steps('exist') && (con = con.steps('detach'));
            con.steps('detach', con);
            // 外层的包裹
            var shadCon = $('<div style="text-align: center;margin-bottom: 5px"></div>');
            con.parent().append(shadCon);
            var addStepBtn = $(option.btn.formatter(option.btn.text));
            addStepBtn.hasClass('easyui-linkbutton') && (addStepBtn = addStepBtn.linkbutton({}));
            // 添加按钮事件
            var add = function () {
                var cur_step = currentStep.call(addStepBtn);
                var initStepIndex = function (idx) {
                    var index = $(option.index.formatter(idx));
                    index.hasClass('easyui-textbox') && (index = index.textbox({}), index.toggle());
                    return index;
                }
                var shadDiv = $('<div/>'),
                    index = initStepIndex(cur_step),
                    namedCtrls = {};
                shadDiv.append(index);
                if (option.ctrls && option.ctrls.length) {
                    option.ctrls.map(function (opt) {
                        var ctrl = opt.type !== 'label' ? $('<input>') : $('<label></label>');
                        shadDiv.append(ctrl);
                        opt.init && opt.init.call(ctrl, opt);
                        opt.name && opt.name.length && (namedCtrls[opt.name] = ctrl);
                    })
                }
                var deleteBtn = $('<a>删除</a>');
                deleteBtn.css('margin-left', '10px');
                shadDiv.append(deleteBtn);
                deleteBtn.linkbutton({});
                con.append(shadDiv);
                // 删除按钮事件
                deleteBtn.click(function () {
                    var nexts = shadDiv.nextAll(),
                        startIndex = currentStep.call(addStepBtn) - 1 - nexts.length;
                    nexts.each(function (i, div) {
                        $(div).children(':first').replaceWith(initStepIndex(startIndex + i));
                    });
                    shadDiv.remove();
                    currentStep.call(addStepBtn, currentStep.call(addStepBtn) - 1);
                    option.btn.remove_click && option.btn.remove_click.call(deleteBtn, startIndex, currentStep.call(addStepBtn) - 1);
                });
                option.btn.add_click && option.btn.add_click.call(addStepBtn, cur_step, namedCtrls);
                currentStep.call(addStepBtn, cur_step + 1);
                return shadDiv;
            }
            con.steps('add', add);
            addStepBtn.click(add);
            shadCon.append(con).append(addStepBtn);
            initReady && $.isFunction(initReady) && initReady.call(con);
            return con;
        }
    }

    var methods = {
        add: function (addfunc) {
            var th = $(this);
            if ($.isFunction(addfunc)) {
                th.data('add', addfunc);
            } else if (th.data('add')) {
                return th.data('add')();
            }
        },
        options: function (option) {
            var th = $(this);
            if (option) {
                th.data('options', option);
                return option;
            }
            return th.data('options');
        },
        detach: function (dom) {
            // console.info(dom);
            var th = $(this);
            if (!th.data('detach') && dom) {
                dom.length && th.data('detach', dom[0].outerHTML);
                !dom.length && console.warn('invalid document object');
            } else if (th.data('detach') && !dom) {
                var newCon = $(th.data('detach'));
                th.parent().replaceWith(newCon);
                th.data('add', null);
                th.data('options', null);
                return newCon;
            }
        },
        load: function (data) {
            var th = $(this);
            // console.info(th);
            if ($.isFunction(methods['add'])) {
                $.isPlainObject(data) && methods.add.call(th).form('load', data);
                if ($.isArray(data) && data.length) {
                    data.map(function (o) {
                        methods.add.call(th).form('load', o);
                    })
                }
            }
        },
        exist: function () {
            var th = $(this);
            return !!th.data('detach');
        }
    }

    function invoke(method, argv) {
        // console.dir(this);
        if (!method) {
            return;
        }
        var container = $(this);
        if (typeof method == 'string') {
            return methods[method].apply(container, [argv])
        }
        var option = parseOption(method);
        initWrapper.apply(container, [option, argv]);
        container.steps('options', option);
    }

    $.fn.steps = $.fn.steps || invoke;
})(jQuery);